package com.jd.fruit.model.admin.order;

import java.util.Date;
import java.util.List;

import com.jd.fruit.common.annotation.Table;
import com.jd.fruit.common.model.BaseModel;
import com.jd.fruit.common.util.StringUtil;
import com.jd.fruit.controller.mobile.CartEntity;
import com.jfinal.kit.StrKit;

/**
 * 购物车管理
 * 
 * @author admin
 * 
 */
@SuppressWarnings("serial")
@Table("t_shopping_cart")
public class ShoppingCart extends BaseModel<ShoppingCart> {

	public static final ShoppingCart dao = new ShoppingCart();
	// 网页购物车是否选中属性
//	private boolean checked = false;

	public ShoppingCart() {

	}

	public ShoppingCart(String goodsId, int goodsNumber, String userId) {
		this.set("goods_sku_id", goodsId);
		this.set("goods_number", goodsNumber);
		this.set("user_id", userId);
	}

	public boolean save(ShoppingCart cartItem) {
		try {
			cartItem.set("id", StringUtil.getKey());
			cartItem.set("input_date", new Date());
			return cartItem.save();
		} catch (Exception e) {
			throw new RuntimeException("购物车保存异常!", e);
		}
	}
	
	public void addCartItem(String goodsId, int goodsNumber,String userId){
		ShoppingCart cart = findFirst("SELECT * FROM t_shopping_cart WHERE goods_sku_id = ? AND user_id = ? ",goodsId, userId);
		if(null!=cart){
			int oldGoodsNumber = cart.getInt("goods_number");
			cart.set("goods_number", goodsNumber + oldGoodsNumber);
			cart.update();
		}else {
			ShoppingCart newcart = new ShoppingCart(goodsId,goodsNumber,userId);
			newcart.set("is_checked", "1");
			this.save(newcart);
		}
	}
	
	public void updateCartItem(String goodsId, int goodsNumber,String userId){
		ShoppingCart cart = findFirst("SELECT * FROM t_shopping_cart WHERE goods_sku_id = ? AND user_id = ? ",goodsId, userId);
		int oldGoodsNumber = cart.getInt("goods_number");
		goodsNumber = goodsNumber + oldGoodsNumber;
		if(goodsNumber<=0){
			cart.delete();
		}else{
			cart.set("goods_number", goodsNumber );
			cart.update();
		}
	}
	
	public void removeCartItem(String cartId){
		ShoppingCart.dao.deleteById(cartId);
	}
	
	


	public void persistCartEntity(CartEntity cartEntity, String userId) {
		List<ShoppingCart> items = cartEntity.getItems();
		for (ShoppingCart cart : items) {
			if (StrKit.notBlank(cart.getStr("id"))) {
				cart.update();
			} else {
				ShoppingCart.dao.save(cart);
			}
		}
	}

	@Override
	public void initWhere() {
		if (StrKit.notBlank(this.getStr("user_id"))) {
			appendSql("AND", "user_id", "=", getStr("user_id"));
		}

		if (StrKit.notBlank(this.getStr("goods_sku_id"))) {
			appendSql("AND", "goods_sku_id", "=", getStr("goods_sku_id"));
		}
	}

	@Override
	public boolean equals(Object obj) {
		return ((ShoppingCart) obj).getStr("goods_sku_id").equals(
				this.getStr("goods_sku_id"));
	}

//	public boolean isChecked() {
//		return checked;
//	}
//
//	public void setChecked(boolean checked) {
//		this.checked = checked;
//	}

}
